﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using System.Collections.Generic;
using Sebarf.Core.Interfaces;
using Sebarf.Services.Interfaces;
using Sebastof.Serialisation;
using Sebastof.Services.Interfaces;
using Utils;

#endregion

namespace Sebastof.ProcessChains.ProcessSteps {
	/// <summary>
	/// Description of the class
	/// </summary>
	public class UnDecorateObject : ProcessStepConverter<ObjectTransportContainer, Object> {
		#region Public Properties

		[ServiceRequest]
		public IServiceLocatorService ServiceLocatorService { get; set; }

		[ServiceRequest]
		public ISerializationDataHandlingStrategyService SerializationDataHandlingStrategyService {
			get { return m_dataHandlingStrategyService; }
			set { m_dataHandlingStrategyService = value; }
		}

		[ServiceRequest]
		public IObjectTreeFlattenerService ObjectTreeHelperService {
			get { return m_objectTreeHelperService; }
			set { m_objectTreeHelperService = value; }
		}

		#endregion

		#region Public Methods

		public UnDecorateObject(IServiceLocatorService serviceLocator) {
			ServiceLocatorService = serviceLocator;
			m_dataHandlingStrategyService = serviceLocator.GetRegisteredService<ISerializationDataHandlingStrategyService>();
			m_objectTreeHelperService = serviceLocator.GetRegisteredService<IObjectTreeFlattenerService>();
		}

		public UnDecorateObject() {
		}

		protected override Object Convert(ObjectTransportContainer toProcess) {
			foreach (object o in toProcess.TransferedMetadata.GetAllObjects()) {
				IList<IFlattenTreeObjectEntry> nestedobjs = m_objectTreeHelperService.GetFlattenTree(o);
				foreach (IFlattenTreeObjectEntry entry in nestedobjs) {
					object nestedo = entry.ObjectTreeEntry;
					if (nestedo is SebastofApplicationObject) {
						var iObject = nestedo as SebastofApplicationObject;
						iObject.AttachedServiceLocatorService = ServiceLocatorService;
						m_dataHandlingStrategyService.RestoreObjectFromTransferedData(nestedo, toProcess.TransferedData[iObject.Id]);
					}
				}
			}
			//TODO: MetadataContext.SetMetadata(toProcess, toProcess.m_metactx.GetMetadata(toProcess));
			return (toProcess).Value;
		}

		#endregion

		#region Private Fields

		[NonSerialized]
		private ISerializationDataHandlingStrategyService m_dataHandlingStrategyService;

		[NonSerialized]
		private IObjectTreeFlattenerService m_objectTreeHelperService;

		#endregion
	}
}